package com.chenxin.wms.process.task.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.exception.wms.WmsException;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.wms.domain.WcsTaskEntity;
import com.chenxin.wms.mapper.WcsTaskMapper;
import com.chenxin.wms.process.task.IWcsTaskProcess;
import org.springframework.stereotype.Service;

@Service
public class IWcsTaskProcessImpl implements IWcsTaskProcess {
    private final WcsTaskMapper wcsTaskMapper;

    public IWcsTaskProcessImpl(WcsTaskMapper wcsTaskMapper) {
        this.wcsTaskMapper = wcsTaskMapper;
    }

    @Override
    public Long procWmsToWcsInsert(WcsTaskEntity wcsTaskEntity) {
        if (wcsTaskEntity == null) {
            throw new WmsException("toWcsTaskInsert001", "设备搬送任务不能为空");
        }
        String requestPk = wcsTaskEntity.getRequestPk();
        String contNo = wcsTaskEntity.getContNo();
        if (StringUtils.isNull(contNo)) {
            throw new WmsException("toWcsTaskInsert004", "容器条码不能为空");
        }
        // 1.检查RPK是否存在
        QueryWrapper<WcsTaskEntity> requestPkQW = new QueryWrapper<>();
        requestPkQW.lambda().eq(WcsTaskEntity::getRequestPk, requestPk);
        Long pkCount = wcsTaskMapper.selectCount(requestPkQW);
        if (pkCount > 0) {
            throw new WmsException("toWcsTaskInsert002", "请求PK【" + requestPk + "】已经存在");
        }
        // 2.检查LPN是否存在未下发的任务
        QueryWrapper<WcsTaskEntity> contNoQw = new QueryWrapper<>();
        contNoQw.lambda().eq(WcsTaskEntity::getContNo, contNo)
                .le(WcsTaskEntity::getTrkStatus, WmsConstants.TASK_STATUS_DONE);
        Long taskCont = wcsTaskMapper.selectCount(contNoQw);
        if (taskCont > 0) {
            throw new WmsException("容器【" + contNo + "】已存在搬送任务!");
        }
        // 3.写入数据库
        int rows = wcsTaskMapper.insert(wcsTaskEntity);
        if (rows <= 0) {
            throw new WmsException("toWcsTaskInsert004", "写入【任务信息】失败");
        }
        // 返回成功写入的任务ID
        return wcsTaskEntity.getTrkId();
    }
}
